package common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理器工具类
 * 使用ThreadLocal保存每个线程独立的数据库连接，保证事务隔离性
 */
public class TransactionManager {

    // 每个线程持有一个独立的Connection
    private static final ThreadLocal<Connection> connectionHolder = new ThreadLocal<>();
    private static final Logger logger = LoggerFactory.getLogger(TransactionManager.class);

    /**
     * 开启事务
     * 从连接池获取连接并关闭自动提交
     */
    public static void beginTransaction() throws SQLException {
        Connection conn = DBUtil.getConnection();
        conn.setAutoCommit(false); // 禁止自动提交，手动控制事务
        connectionHolder.set(conn);
    }

    /**
     * 提交事务
     */
    public static void commit() throws SQLException {
        Connection conn = connectionHolder.get();
        if (conn != null) {
            conn.commit();
        }
    }

    /**
     * 回滚事务
     */
    public static void rollback() {
        Connection conn = connectionHolder.get();
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                logger.error("回滚事务时出错", e);
            }
        }
    }

    /**
     * 结束事务
     * 重置自动提交并关闭连接
     */
    public static void endTransaction() {
        Connection conn = connectionHolder.get();
        if (conn != null) {
            try {
                conn.setAutoCommit(true); // 恢复自动提交
                conn.close(); // 归还连接到连接池
            } catch (SQLException e) {
                logger.error("结束事务时出错", e);
            } finally {
                connectionHolder.remove(); // 移除ThreadLocal中的连接，防止内存泄漏
            }
        }
    }

    /**
     * 获取当前线程绑定的Connection
     * @return Connection 对象
     */
    public static Connection getConnection() {
        return connectionHolder.get();
    }
}
